package net.devkit.common.toolkit;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * 封装Sql/Hql语句的查询条件
 * 
 * @author szy 2012-7-7
 */
public class FilterCollection {

	private StringBuilder whereClause = new StringBuilder();
	private List<Object> args = new ArrayList<Object>();

	public FilterCollection() {
		super();
	}

	public FilterCollection(String filter, Object... params) {
		super();
		addFilter(filter, params);
	}

	public FilterCollection addFilter(String filter, Object... params) {
		if (StringUtils.isBlank(filter)) {
			return this;
		}
		if (whereClause.length() == 0) {
			whereClause.append(" WHERE ").append(filter);
		} else {
			whereClause.append(" AND ").append(filter);
		}

		if (DevTool.isNotEmpty(params)) {
			for (Object param : params) {
				args.add(param);
			}
		}

		return this;
	}

	public FilterCollection addOrder(String filename, String orderrule) {
		if (StringUtils.isBlank(filename)) {
			return this;
		}

		if (this.getWhereClause().toString()
				.matches("^.*order\\s{1}by\\s{1}.*$")) {
			whereClause.append(" , ").append(filename).append(" ")
					.append(orderrule);
		} else {
			whereClause.append(" order by ").append(filename).append(" ")
					.append(orderrule);
		}
		return this;
	}

	public FilterCollection addOrder(String[] sortname, String[] sortorder) {
		if (DevTool.isEmpty(sortname))
			return this;
		int len = sortname.length;
		for (int c = 0; c < len; c++) {
			if (c == 0)
				whereClause.append(" order by ").append(sortname[0])
						.append(" ").append(sortorder[0]);
			else
				whereClause.append(" , ").append(sortname[c]).append(" ")
						.append(sortorder[c]);
		}
		return this;
	}

	public StringBuilder getWhereClause() {
		return whereClause;
	}

	public List<Object> getArgs() {
		return args;
	}

}
